<template>
  <div class="CreateDirectly">
    <el-dialog append-to-body destroy-on-close v-model="confirmDialog" title="日志" width="500" center>
      <el-input :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入日志" maxlength="500" show-word-limit autosize
                v-model="publishLog" type="textarea"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="publishCancel">取消</el-button>
          <el-button size="small" :disabled="!publishLog" type="primary" @click="confirmPublish">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 步骤导航 -->
    <div class="steps-section">
      <el-row :gutter="20">
        <el-col :span="12" :offset="6">
          <div class="step-container">
            <el-steps :active="activeStep" align-center>
              <el-step title="基础设置" @click="handleStepClick('basicSetting')">
                <template #icon>
                  <div class="custom-icon">1</div>
                </template>
              </el-step>
              <el-step title="表单设计" @click="handleStepClick('formDesign')">
                <template #icon>
                  <div class="custom-icon">2</div>
                </template>
              </el-step>
              <el-step title="流程设计" @click="handleStepClick('processDesign')">
                <template #icon>
                  <div class="custom-icon">3</div>
                </template>
              </el-step>
              <el-step title="高级设置" @click="handleStepClick('advancedSetting')">
                <template #icon>
                  <div class="custom-icon">4</div>
                </template>
              </el-step>
            </el-steps>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="action-buttons">
            <el-button size="large" type="primary" @click="publish">发布</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="content-bottom" v-loading="loading" style="min-height: 500px">
      <template v-if="!loading">
        <BasicSetting :conf="_mockData.basicSetting" tabName="basicSetting" ref="basicSetting"
                      v-show="activeStep === 0"/>
        <GeneratorForm :conf="_mockData.formData" tabName="formDesign" ref="formDesign" v-show="activeStep === 1"/>
        <Process tabName="processDesign" ref="processDesign" :conf="_mockData.processData"
                 v-show="activeStep === 2"/>
        <AdvancedSetting tabName="advancedSetting" ref="advancedSetting" :conf="_mockData.advancedSetting"
                         v-show="activeStep === 3"/>
      </template>
    </div>
  </div>
</template>
<script setup name="CreateDirectly">
import * as _ from 'lodash'
import {ref} from 'vue'
import BasicSetting from './basicSetting'
import GeneratorForm from './generatorForm'
import AdvancedSetting from './AdvancedSetting'
import Process from "@/views/flow/createDirectly/Process";
import {mockData} from "@/views/flow/createDirectly/generatorForm/FormRender/mockConf.js";
import {
  ElMessage,
  ElNotification
} from "element-plus";
import moment from "moment";
import {
  flowApprover,
  flowApproverDetail
} from "@/api/flow/approver.js";
import {
  createTemplate,
  editTemplate,
  templateDetail
} from "@/api/flow/template.js";
import {
  autoOperate, getformFields,
  getformid
} from "@/views/flow/tool.js";
import {G} from "@/views/flow/globalVar.js";
const {proxy} = getCurrentInstance();
const loading = ref(false)
const confirmDialog = ref(false)
const emit = defineEmits(['createSuccess',
  'createFail'])
const props = defineProps({
  //直接创建 createDirectly
  //新建经典模板 newClassicTemplate
  //新建经典模板 newClassicTemplate
  //修改经典模板 editClassicTemplate
  //使用经典模板 useClassicTemplate
  //修改现有流程 modifyExistingProcess
  //复用现有流程 reuseExistingProcesses
  createApproverType: {
    type: [String],
    default: G.CREATE_APPROVER_TYPE.CREATE_DIRECTLY
  },
  tplId: {
    type: [String,
      Number],
    default: ''
  },
  editId: {
    type: [String,
      Number],
    default: ''
  },
})
const flowNo = ref(undefined)
const activeStep = ref(0)
const _mockData = ref(mockData)
const getActiveStep = (tabName) => {
  switch (tabName) {
    case 'basicSetting':
      return 0
    case 'formDesign':
      return 1
    case 'processDesign':
      return 2
    case 'advancedSetting':
      return 3
  }
}
//更新日志
const publishLog = ref("")
const handleStepClick = (step) => {
  activeStep.value = getActiveStep(step)
}
const basicSetting = ref(undefined)
const formDesign = ref(undefined)
const processDesign = ref(undefined)
const publishCancel = () => {
  confirmDialog.value = false
  publishLog.value = ""
}
let getFlowParams = ref(undefined)
const publish = () => {
  getFlowParams.value = undefined
  publishLog.value = ""
  const getCmpData = name => {
    if (!proxy.$refs[name] || !proxy.$refs[name].getData) return
    let data = proxy.$refs[name].getData()
    return data
  }
  const p1 = getCmpData('basicSetting')
  const p2 = getCmpData('formDesign')
  const p3 = getCmpData('processDesign')
  Promise.all([p1,
    p2,
    p3])
      .then(res => {
        confirmDialog.value = true
        getFlowParams.value = {
          basicSetting: res[0].formData,//p1
          processData: res[2].formData,//p2
          formData: res[1].formData,//p3
          advancedSetting: getCmpData('advancedSetting')
        }
      })
      .catch(err => {
        confirmDialog.value = false
        if (err.target) {
          activeStep.value = getActiveStep(err.target)
        }
        if (err.msg) {
          ElMessage.warning(err.msg)
        } else {
          ElMessage.warning("表单出错！")
        }
      })
}
const confirmPublish = () => {
  sendToServer(getFlowParams.value)
}
const createSuccess = () => {
  emit('createSuccess')
}
const createFail = () => {
  emit('createFail')
}

const convertData = (param) => {
  let obj = {}
  for (var i in param) {
    //基础设置
    if (i == 'basicSetting') {
      obj['basicSetting'] = param['basicSetting']
    }
    //流程设计
    else if (i == 'processData') {
      obj['processData'] = param['processData']
    }
    //表单设计
    else if (i == 'formData') {
      obj['formData'] = param['formData']
    }
    //高级设置
    else if (i == 'advancedSetting') {
      obj['advancedSetting'] = param['advancedSetting']
    }
  }
  let formIdArr = []
  let formFields = []
  getformid(obj.formData.fields,
      formIdArr)
  getformFields(obj.formData.fields,
      formFields)
  autoOperate(obj.processData,
      formIdArr, formFields)
  return obj
}
const sendToServer = (param) => {
  loading.value = true
  ElNotification.success({
    title: '保存成功',
    message: moment(new Date)
        .format('YYYY-MM-DD HH:mm:ss'),
    position: 'bottom-right'
  })
  var _param = _.cloneDeep(param)
  let result = convertData(_param,
      true)
  result['revise'] = publishLog.value
  console.log('配置数据',
      result)
  if (props.createApproverType) {
    switch (props.createApproverType) {
        //直接创建
      case 'createDirectly': {
        //创建流程
        flowApprover(result)
            .then(res => {
              createSuccess()
            })
            .catch((error) => {
              createFail(error)
            })
            .finally(res => {
              loading.value = false
            })
        break
      }
        //新建经典模板
      case 'newClassicTemplate': {
        delete result.basicSetting.id
        createTemplate({
          json: JSON.stringify(result),
          tmeplateName: result.basicSetting.flowName,
          description: result.basicSetting.flowRemark,
          flowImg: result.basicSetting.flowImg,
          revise: publishLog.value
        })
            .then(res => {
              createSuccess()
            })
            .catch((error) => {
              createFail(error)
            })
            .finally(res => {
              loading.value = false
            })
        break
      }
        //使用经典模板
      case 'useClassicTemplate': {
        delete result.basicSetting.id
        flowApprover(result)
            .then(res => {
              createSuccess()
            })
            .catch((error) => {
              createFail(error)
            })
            .finally(res => {
              loading.value = false
            })
        break
      }

        //修改经典模板
      case 'editClassicTemplate': {
        delete result.basicSetting.id
        editTemplate({
          id: props.tplId,
          json: JSON.stringify(result),
          tmeplateName: result.basicSetting.flowName,
          flowImg: result.basicSetting.flowImg,
          revise: publishLog.value
        })
            .then(res => {
              createSuccess()
            })
            .catch((error) => {
              createFail(error)
            })
            .finally(res => {
              loading.value = false
            })
        break
      }

        //修改现有流程
      case 'modifyExistingProcess': {
        //创建流程
        flowApprover(result)
            .then(res => {
              createSuccess()
            })
            .catch((error) => {
              createFail(error)
            })
            .finally(res => {
              loading.value = false
            })
        break
      }
        //复用现有流程
      case 'reuseExistingProcesses': {
        delete result.basicSetting.id
        //创建流程
        flowApprover(result)
            .then(res => {
              createSuccess()
            })
            .catch((error) => {
              createFail(error)
            })
            .finally(res => {
              loading.value = false
            })
        break
      }
    }
  }
}
const setIdGenerator = () => {
  if (!!_mockData.value.processData && JSON.stringify(_mockData.value.processData) != '{}') {
    let str = JSON.stringify(_mockData.value.processData)
    let arr = str.match(/"nodeId":"[^"]+/gi)
    let ls = arr.map((item,
                      index) => {
      return item.split('"nodeId":"')[1]
    })
    window.localStorage.setItem('idGenerator',
        JSON.stringify(ls))
  }
}
const showContent = () => {
  loading.value = true
  _mockData.value = null
  if (props.createApproverType) {
    switch (props.createApproverType) {
        //直接创建
      case 'createDirectly': {
        _mockData.value = JSON.parse(JSON.stringify(mockData))
        setIdGenerator()
        flowNo.value = undefined
        loading.value = false
        break
      }
        //新建经典模板
      case 'newClassicTemplate': {
        _mockData.value = JSON.parse(JSON.stringify(mockData))
        setIdGenerator()
        flowNo.value = undefined
        loading.value = false
        break
      }

        //修改经典模板
      case 'editClassicTemplate': {
        templateDetail(props.tplId)
            .then(res => {
              _mockData.value = JSON.parse(JSON.stringify(convertData(JSON.parse(res.data.json),
                  false)))
              setIdGenerator()
              flowNo.value = res.data.flowNo
              loading.value = false
            })
        break
      }

        //使用经典模板
      case 'useClassicTemplate': {
        templateDetail(props.tplId)
            .then(res => {
              _mockData.value = JSON.parse(JSON.stringify(convertData(JSON.parse(res.data.json),
                  false)))
              setIdGenerator()
              flowNo.value = res.data.flowNo
              loading.value = false
            })
        break
      }
        //修改现有流程
      case 'modifyExistingProcess': {
        flowApproverDetail(props.editId)
            .then(res => {
              _mockData.value = JSON.parse(JSON.stringify(convertData(res.data,
                  false)))
              setIdGenerator()
              flowNo.value = res.data.flowNo
              loading.value = false
            })
        break
      }
        //复用现有流程
      case 'reuseExistingProcesses': {
        flowApproverDetail(props.editId)
            .then(res => {
              _mockData.value = JSON.parse(JSON.stringify(convertData(res.data,
                  false)))
              setIdGenerator()
              flowNo.value = res.data.flowNo
              loading.value = false
            })
        break
      }
    }
  }
}
onMounted(() => {
  showContent()
})
</script>
<style lang="scss" scoped>
.CreateDirectly {
  height: 100%;
  width: 100%;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  .steps-section {
    border: 1px solid rgb(235, 237, 240);
    background: white;
    padding: 10px 0px;
    width: 100%;
    .step-container {
      width: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
    :deep(.el-steps) {
      flex: 1;
      max-width: 800px;
    }
    :deep(.el-step__title.is-process) {
      color: #1890ff;
      font-weight: 500;
    }
    .action-buttons {
      display: flex;
      height: 100%;
      justify-content: flex-end;
      align-items: center;
      & > * {
        margin-right: 24px;
      }
    }
  }
  .content-bottom {
    width: 100%;
    flex: 1 1 100%;
    overflow: hidden;
  }
  .custom-icon {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #c0c4cc;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
  }
  :deep(.el-step__head) {
    cursor: pointer;
    &.is-process .custom-icon {
      background-color: #1890ff;
    }
    &.is-finish .custom-icon {
      background-color: #1890ff;
    }
  }
}
</style>

